import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../store/user.dart';
import '../utils/network_manager.dart';

class ApiService {
  final Dio _dio;

  ApiService() : _dio = Dio() {
    // 设置基本配置
    _dio.options.baseUrl = 'http://192.168.2.4:3000/v1';
    _dio.options.connectTimeout = Duration(milliseconds: 5000);
    _dio.options.receiveTimeout = Duration(milliseconds: 3000);
    _dio.interceptors.add(InterceptorsWrapper(
      // 请求拦截
      onRequest: (options, handler) async {
        print("请求 URL: ${options.uri}");
        print("请求参数: ${options.data}");
        // options.headers['Authorization'] = UserStore.getUserInfo()['token'];
        options.headers['Authorization'] = UserStore.getUserInfo().token;
        if(!await NetworkManager().hasConnection()){
          SmartDialog.showToast(
            '请检查网络连接',
            alignment: Alignment.topCenter,
          );
        }
        return handler.next(options); // 必须调用 handler.next(options)
      },
      // 响应拦截
      onResponse: (response, handler) {
        if (response.statusCode! >= 300) {
          print("请求失败");
          SmartDialog.showToast(
            response.data.msg,
            alignment: Alignment.topCenter,
          );
        }
        return handler.next(response); // 必须调用 handler.next(response)
      },
      // 错误拦截
      onError: (DioException e, handler) {
        print("请求错误: ${e.message}");
        SmartDialog.showToast(
          '服务器连接失败...',
          alignment: Alignment.topCenter,
        );
        return handler.next(e); // 必须调用 handler.next(e)
      },
    ));
  }

  // 通用 GET 请求
  Future<Response> get(String endpoint, {Map<String, dynamic>? queryParams}) async {
    Response response = await _dio.get(endpoint, queryParameters: queryParams);
    return response;
  }

  // 通用 POST 请求
  Future<Response> post(String endpoint, {Map<String, dynamic>? data}) async {
    debugPrint('post');
    Response response = await _dio.post(endpoint, data: data);
    return response;
  }

  // 通用 PUT 请求
  Future<Response> put(String endpoint, {Map<String, dynamic>? data}) async {
    Response response = await _dio.put(endpoint, data: data);
    return response;
  }

  // 通用 DELETE 请求
  Future<Response> delete(String endpoint, {Map<String, dynamic>? data}) async {
    Response response = await _dio.delete(endpoint, data: data);
    return response;
  }
}